package com.zidian.study.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.ImagePikerAdapter;
import com.zidian.study.event.DeleteImageEvent;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.DateCheckUtil;
import com.zidian.study.utils.FileUtils;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ImageFactory;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zidian.study.utils.RegexUtils;
import com.zidian.study.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 添加活动
 * Created by GongCheng on 2016/11/23.
 */

public class AddTaskActivity extends ToolBarActivity {
    @Bind(R.id.action_title_et)
    EditText actionTitleEt;
    @Bind(R.id.action_date_Tv)
    TextView actionDateTv;
    @Bind(R.id.action_place_et)
    EditText actionPlaceEt;
    @Bind(R.id.action_people_et)
    EditText actionPeopleEt;
    @Bind(R.id.action_phone_et)
    EditText actionPhoneEt;
    @Bind(R.id.action_content_et)
    EditText actionContentEt;
    @Bind(R.id.photo_preview_list_rv)
    RecyclerView photoPreviewListRv;

    private static final int REQUEST_CODE = 0;

    private ImagePikerAdapter adapter;
    private List<String> images;
    private ImageFactory imageFactory;
    //日期选择
    private DateCheckUtil dateCheckUtil;
    private int year;
    private int month;
    private int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_add_task);
        ButterKnife.bind(this);
        imageFactory = new ImageFactory();
        images = new ArrayList<>();
        setTitle("发布活动");
        adapter = new ImagePikerAdapter(this);
        RecyclerView.LayoutManager layoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        photoPreviewListRv.setLayoutManager(layoutManager);
        photoPreviewListRv.setAdapter(adapter);
        adapter.setOnItemClickListener(new ImagePikerAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                if (images.size() == position) {
                    pickImages();
                } else {
                    Intent intent = new Intent(context, NewPhotoActivity.class);
                    intent.putExtra("imagePath", images.get(position));
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        });

        EventBus.getDefault().register(this);

        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DATE);
        dateCheckUtil = new DateCheckUtil(this, actionDateTv);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteImage(DeleteImageEvent event) {
        if (event.getPosition() != -1) {
            images.remove(event.getPosition());
            adapter.setImages(images);
        }
    }

    @OnClick(R.id.action_commit_bt)
    public void commit() {
        publishActivity();
    }

    /**
     * 图片加载器
     */
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    /**
     * 图片选择器
     */
    private void pickImages() {
        ImgSelConfig config = new ImgSelConfig.Builder(loader)
                // 是否多选
                .multiSelect(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                //statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#25bf7f"))
                .cropSize(1, 1, 800, 450)
                .needCrop(false)
                // 第一个是否显示相机
                .needCamera(true)
                // 最大选择图片数量
                .maxNum(5)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

            for (String path : pathList) {
                images.add(path);
            }
            adapter.setImages(images);
            //            File file2 = new File(images.get(0));
            //         FileUtilsOld.formatFileSizeToString(file2.length());

        }
    }

    /**
     * 选择活动日期及时间
     */
    @OnClick(R.id.action_date_Tv)
    public void pickDate() {
        dateCheckUtil.clickBirthday(year, month, day);
    }

    /**
     * 压缩图片
     */
    private List<String> compressImages(List<String> images) {
        List<String> newImages = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String newPath = com.yuyh.library.imgsel.utils.FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg";
            try {
                imageFactory.compressAndGenImage(images.get(i),
                        newPath, 100, false);
                newImages.add(newPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return newImages;
    }

    /**
     * 发布活动
     */
    private void publishActivity() {

        String title = actionTitleEt.getText().toString().trim();
        String place = actionPlaceEt.getText().toString().trim();
        String total = actionPeopleEt.getText().toString().trim();
        String phoneNumber = actionPhoneEt.getText().toString().trim();
        String content = actionContentEt.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            Snackbar.make(actionContentEt, "标题不能为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(place)) {
            Snackbar.make(actionContentEt, "地点不能为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(total)) {
            Snackbar.make(actionContentEt, "总数不能为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (!RegexUtils.isMobileExact(phoneNumber)) {
            Snackbar.make(actionContentEt, "请输入正确的手机号码", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(content)) {
            Snackbar.make(actionContentEt, "内容不能为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (title.length() > 15) {
            Snackbar.make(actionContentEt, "标题不能超过15个字符!", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (place.length() > 25) {
            Snackbar.make(actionContentEt, "地点不能超过25个字符!", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (content.length() > 500) {
            Snackbar.make(actionContentEt, "活动内容不能超过500个字符", Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (images.size() < 2) {
            Snackbar.make(actionContentEt, "请至少添加2张图片", Snackbar.LENGTH_SHORT).show();
            return;
        }
        String url = Constant.URL_GOAL + "activity/add";
        Map<String, String> map = new HashMap<>();
        map.put("studentId", GetUserInfo.getAccount(context));
        map.put("token", GetUserInfo.getToken(context));
        map.put("activityTitle", title);
        map.put("activityLocation", place);
        map.put("activityContent", content);
        map.put("functionAttendanceSum", total);
        map.put("activityCollegeNumber", phoneNumber);
        map.put("activityTime", actionDateTv.getText().toString());

        List<String> newImages = compressImages(images);
        File file1 = new File(newImages.get(0));

        Log.e("Time", FileUtils.formatFileSizeToString(file1.length()));
        Map<String, File> files = new HashMap<>();
        for (int i = 1; i < newImages.size(); i++) {
            files.put("file" + i, new File(newImages.get(i)));
        }
        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post()
                .url(url)
                .files("files", files)
                .addFile("file1", "file0", file1)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarBlackUtil.loadCancel();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("code") == 200) {
                                ToastUtil.showToast(context, "活动提交成功，等待审核");
                                ProgressBarBlackUtil.loadCancel();
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
